const mysql = require('mysql2/promise');
const dotenv = require('dotenv');

dotenv.config({ path: '.env.local' });

async function fixJsonFields() {
  try {
    console.log('连接数据库...');
    const connection = await mysql.createConnection({
      host: process.env.DB_HOST || 'rm-bp14wd51i709c3z79ho.mysql.rds.aliyuncs.com',
      user: process.env.DB_USER || 'root',
      password: process.env.DB_PASSWORD || 'Ircnjfdhnvxwz@123',
      database: process.env.DB_NAME || 'xiaoyoubao',
      port: Number(process.env.DB_PORT) || 3306
    });
    
    console.log('数据库连接成功');
    
    // 查询所有政策
    const [policies] = await connection.execute('SELECT id, key_points, requirements FROM enterprise_policies');
    console.log(`找到 ${policies.length} 条政策记录`);
    
    // 修复每个政策的JSON字段
    for (const policy of policies) {
      try {
        // 检查并修复key_points字段
        let keyPoints = [];
        if (policy.key_points) {
          try {
            // 尝试解析现有JSON
            keyPoints = JSON.parse(policy.key_points);
          } catch (error) {
            console.error(`政策ID ${policy.id} 的key_points不是有效的JSON:`, policy.key_points);
            // 如果无法解析，将字符串格式化为数组
            if (typeof policy.key_points === 'string') {
              keyPoints = [policy.key_points];
            }
          }
        }
        
        // 检查并修复requirements字段
        let requirements = [];
        if (policy.requirements) {
          try {
            // 尝试解析现有JSON
            requirements = JSON.parse(policy.requirements);
          } catch (error) {
            console.error(`政策ID ${policy.id} 的requirements不是有效的JSON:`, policy.requirements);
            // 如果无法解析，将字符串格式化为数组
            if (typeof policy.requirements === 'string') {
              requirements = [policy.requirements];
            }
          }
        }
        
        // 更新记录
        const keyPointsJson = JSON.stringify(keyPoints);
        const requirementsJson = JSON.stringify(requirements);
        
        await connection.execute(
          'UPDATE enterprise_policies SET key_points = ?, requirements = ? WHERE id = ?',
          [keyPointsJson, requirementsJson, policy.id]
        );
        
        console.log(`已更新政策ID ${policy.id} 的JSON字段`);
      } catch (err) {
        console.error(`处理政策ID ${policy.id} 时出错:`, err);
      }
    }
    
    console.log('所有JSON字段已修复');
    await connection.end();
  } catch (error) {
    console.error('修复JSON字段失败:', error);
  }
}

fixJsonFields(); 